package com.hontech.kaltaapp.ui.parts

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import com.hontech.kaltaapp.R
import com.hontech.kaltaapp.device.event.DeviceStatus
import com.hontech.kaltaapp.ui.view.LabelState
import com.hontech.kaltaapp.utils.register
import com.hontech.kaltaapp.utils.unregister
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class SensorParts (context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {

    private val spWaterHigh: LabelState
    private val spWaterLow: LabelState
    private val spGoSwitch: LabelState
    private val spLeak1: LabelState
    private val spLeak2: LabelState
    private val spBowl: LabelState
    private val spNozzleAlm: LabelState
    private val spNozzleOrigin: LabelState
    private val spNozzleOrigin2: LabelState
    private val spDoorIsClose: LabelState
    private val spDoorIsLock: LabelState

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.parts_sensor, this)
        spWaterHigh = view.findViewById(R.id.id_sensor_ls_water_high)
        spWaterLow = view.findViewById(R.id.id_sensor_ls_water_low)
        spGoSwitch = view.findViewById(R.id.id_sensor_ls_go_switch)
        spLeak1 = view.findViewById(R.id.id_sensor_ls_leak1)
        spLeak2 = view.findViewById(R.id.id_sensor_ls_leak2)
        spBowl = view.findViewById(R.id.id_sensor_ls_bowl)
        spNozzleAlm = view.findViewById(R.id.id_sensor_ls_nozzle_alm)
        spNozzleOrigin = view.findViewById(R.id.id_sensor_ls_origin)
        spNozzleOrigin2 = view.findViewById(R.id.id_sensor_ls_origin2)
        spDoorIsClose = view.findViewById(R.id.id_sensor_door_is_close)
        spDoorIsLock = view.findViewById(R.id.id_sensor_ls_door_is_lock)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onStatusUpdate(status: DeviceStatus) {
        val sensor = status.sensorStatus
        spWaterHigh.set(sensor.waterLevelHigh)
        spWaterLow.set(sensor.waterLevelLow)
        spGoSwitch.set(sensor.goSwitch)
        spLeak1.set(sensor.leak1)
        spLeak2.set(sensor.leak2)
        spBowl.set(sensor.bowlChecked)
        spNozzleAlm.set(sensor.nozzleAlm)
        spNozzleOrigin.set(sensor.nozzleOrigin)
        spNozzleOrigin2.set(sensor.nozzleOrigin2)
        spDoorIsClose.set(sensor.doorIsClose)
        spDoorIsLock.set(sensor.doorIsLock)
    }

    override fun onWindowVisibilityChanged(visibility: Int) {
        super.onWindowVisibilityChanged(visibility)
        if (visibility == VISIBLE) {
            register(this)
        } else {
            unregister(this)
        }
    }
}